package com.csb.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Bean("userRealm")
    public UserRealm userRealm() {
        return new UserRealm();
    }

    @Bean
    public DefaultWebSecurityManager securityManager(UserRealm userRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    /**
     * 路径过滤规则
     *
     * @return
     */
    @Bean(name = "shiroFilterFactoryBean")
    public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager securityManager) {
        // 声明shiro工厂
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        // 创建map集合存放过滤条件
        Map<String, String> map = new LinkedHashMap<>();
        map.put("/static/**", "anon");        // 允许匿名访问
        map.put("/css/**", "anon");        // 允许匿名访问
        map.put("/img/**", "anon");        // 允许匿名访问
        map.put("/js/**", "anon");        // 允许匿名访问
        map.put("/fonts/**", "anon");        // 允许匿名访问
        // 有先后顺序
        map.put("/api/user/add", "anon");      // 允许匿名访问
        map.put("/api/user/login", "anon");      // 允许匿名访问
        map.put("/api/user/chkAccount", "anon");      // 允许匿名访问

        // 配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了
        map.put("/logout", "logout");
        map.put("/**", "authc");        // 进行身份认证后才能访问

        // 设置登陆页
        shiroFilterFactoryBean.setLoginUrl("/index");
        // 将规则放入shiro中
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        // 返回
        return shiroFilterFactoryBean;
    }

    /**
     * 开启Shiro注解模式，可以在Controller中的方法上添加注解
     *
     * @param securityManager
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(@Qualifier("securityManager") DefaultSecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

    /*
     * 配置ShiroDialect，用于Thymeleaf和Shiro标签配合使用
     */
    @Bean
    public ShiroDialect shiroDialect() {
        return new ShiroDialect();
    }
}
